import puppeteer from "puppeteer"
import express from "express"
import config from "./config.js";
// 导入mysql模块
import mysql from 'mysql2/promise';
import { delay, autoScrollZero } from "./util.js"

// 创建一个数据库连接
const connection = await mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: "123456",
    database: 'spider',
});

var browser;

async function bootstrap() {
    browser = await puppeteer.launch({ headless: false, userDataDir: config.localData, defaultViewport: { width: 1600, height: 800 } })
    const page = await browser.newPage()
    await page.goto(config.homePage)
    await run(browser)
}

// 查询所有待执行任务
async function getTasks() {
    let [rows] = await connection.execute('SELECT * FROM `spider`.`order`')
    return rows
}

async function run(browser) {
    const pages = await browser.pages()
    const page = pages[1]

    let title = await page.title()
    // 判断是否在登录页面
    if (title == config.loginPageTitle) {
        return {
            code: 201,
            msg: "当前正处于登录页面，请先登录"
        }
    }
    // 判断是否在首页
    let url = await page.url()

    if (url != config.homePage) {
        page.goto(config.homePage)
    }
    // 查询所有带执行任务
    let res1 = await getTasks()

    let tasks = res1.map(item => {
        return {
            ...item,
            ids: item.order_id.split(',')
        }
    })

    // 循环执行每个tasks
    await loopRunTask(tasks, page)

    return {
        code: 200,
        msg: "执行成功"
    }
}

async function loopRunTask(tasks, page) {

    tasks.map(async item => {

        for (let idx = 0; idx < item.ids.length; idx++) {
            let id = item.ids[idx]

            await page.focus('.search-box');

            await page.keyboard.down('Control');
            await page.keyboard.press('A');
            await page.keyboard.up('Control');
            await page.keyboard.press('Backspace');
            await delay(2000)

            await page.keyboard.type(id);
            await page.keyboard.press('Enter');

            await delay(5000)

            let rows = await page.$$(".linked")
            let preferential = await page.$$(".preferential")
            let onway = await page.$$(".on_way")

            rows = rows.concat(preferential);
            rows = rows.concat(onway);

            if (rows.length == 1) {
                let choice = await page.$$(".andes-checkbox__input")
                if (choice.length == 2) {
                    choice[1].click()
                }
            }
            // 暂停
            await delay(5000)
        }

        await page.focus('.search-box');

        await page.keyboard.down('Control');
        await page.keyboard.press('A');
        await page.keyboard.up('Control');
        await page.keyboard.press('Backspace');
        await delay(2000)
        await page.keyboard.press('Enter');

        await delay(5000)

        // 滚动到顶部
        await autoScrollZero(page, 100)
        // 选择按钮提交
        await page.click("#appointment_button")

        await delay(5000)
        // 跳转第二页执行
        await page.focus(".andes-form-control__field")
        await page.click(".andes-form-control__field")
        // 等待500ms
        await delay(500)
        // 首先这个月每天都点一遍
        let days = await page.$$(".day")
        for (let index = 0; index < days.length; index++) {
            await days[index].click()
            await delay(500)
        }
        // 获取可选择日期
        // 执行选择
        await page.evaluate(() => {
            let days = document.querySelectorAll(".day")
            console.log('days', days)
            days.forEach(item => {
                console.log(item.innerText)
            })
        })

    })
}
// 服务端
const app = express()

app.get('/', async function (_, response) {
    try {
        let res = await run(browser)
        response.send(JSON.stringify(res))
    } catch (error) {
        response.send(error)
    }
})

app.listen(config.port)

bootstrap()